<style type="text/css" title="currentStyle">
	@import "../media/css/demo_page.css";
	@import "../media/css/demo_table_jui.css";
	@import "../examples_support/themes/smoothness/jquery-ui-1.8.4.custom.css";
	@import "media/css/TableTools_JUI.css";
</style>
<script type="text/javascript" charset="utf-8" src="../media/js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf-8" src="media/js/ZeroClipboard.js"></script>
<script type="text/javascript" charset="utf-8" src="media/js/TableTools.js"></script>
<script type="text/javascript" charset="utf-8">
	$(document).ready( function () {
		$('#example').dataTable( {
			"bJQueryUI": true,
			"sPaginationType": "full_numbers",
			"sDom": 'Tlfrtip',
			"oTableTools": {
				"aButtons": [
					"copy", "csv", "xls", "pdf", "print",
					{
						"sExtends":    "collection",
						"sButtonText": "Save",
						"aButtons":    [ "csv", "xls", "pdf" ]
					}
				]
			}
		} );
	} );
</script>

<?php
@set_time_limit(0);

$fr_hr_selected = 'selected';
$fr_min_selected = 'selected';
$to_hr_selected = 'selected';
$to_min_selected = 'selected';

if(isset($_POST[map_filter_btn]) && $_POST[map_filter_btn]!='')
{
  $fr_hr_selected = '';
  $fr_min_selected = '';
  $to_hr_selected = '';
  $to_min_selected = '';
}
function chk_folder($filename)
{
	$fp_load = @fopen("$filename", "rb");
	if ( $fp_load )
	{
		return true;
	}
	else
	{
		return false;
	}
}


function getTripReport($sdate,$userId,$devId,$usrSTime,$usrETime,$flag)
{

$cnt = 1;
$tmp=-1;
$t1=0.0;
$t2=0.0;
$timeArr= array();
$timediff=array();
$strTime='';
$endTime='';
$k1 = 0;
$totDist = 0;
$file = DATAPATH.date('d-m-Y',strtotime($sdate))."/".$devId.".txt";   
//echo "<br><br>";
if(chk_folder($file))
{
	$file1 = @fopen($file, "r");
	if($file1)
	{
		while(!feof($file1))
		{
			$data= fgets($file1);
		}
		$data = getSortedData($data);
	}

	if(count($data)>0)
	{
	 $data1=explode("#",$data);

	 for($j1=0;$j1<count($data1);$j1++)
	 {
		$data2=explode("@",$data1[$j1]);
		if(count($data2)>1)
		{
			$data3=explode(",",$data2[1]);
			//echo date("d-m-Y", strtotime($sdate))."==".date("d-m-Y",@mktime(($data3[4]+5),($data3[5]+30),$data3[6],$data3[2],$data3[1],$data3[3]));
			$device=$data3[0];
			$geodate = $data3[8]." ".$data3[9];
			$geoTime = $data3[9];
			$curTime = explode(":",$data3[9]);
			$curTime = (($curTime[0] * 60) + $curTime[1]);
			
			$pos1=calLat($data3[2]);
			$pos2=calLong($data3[1]);
			
			if($curTime >= $usrSTime && $curTime<=$usrETime)
			{	
			if($pos1>0 && $pos2>0)
			{
			if(!in_array($geoTime,$timeArr))
			{
			//echo $geoTime."	sss ".$data3[3];
			//echo $usrSTime." >= ".$curTime." <= ".$usrETime." ".$totalDistance."<br>";
			//echo "<BR>";
			
			
			if($data3[3] > 0 && $strTime=='')
			{
				$strTime=$geoTime;
				
				//$res2 = getGeocode($latlngloca,'ADDRESS');	//getMyGeoAddress($latlngloca);	
				//$res2='<a href=http://maps.google.com/maps?q='.$pos1.','.$pos2.' target=_blank title=click here>'.$pos1.','.$pos2.'</a>';
				//$strPoint = $res2;				
				$strPoint = getMyGeoAddress($pos1,$pos2);
				$strPt = $pos1.','.$pos2;
				$avgSpeed += $data3[3];
				
				$pits1 =  $pos1;
				$pits2 =  $pos2;
								
				$k1++;
			}
			else if($data3[3] > 0 && $endTime=='' && $strTime!='')
			{
				
				$avgSpeed += intval($data3[3]);
				
				$pits3 =  $pos1;
				$pits4 =  $pos2;
				
				$dist = getDistance($pits1, $pits2, $pits3, $pits4);
				$totDist += $dist;
				$pits1 =  $pits3;
				$pits2 =  $pits4;
				$k1++;

			}
			else if($data3[3] == 0 && $endTime=='' && $strTime!='')
			{
				$endTime=$geoTime;
				//$latlngloca = $pos1.','.$pos2;
				//$res2 = getGeocode($latlngloca,'ADDRESS');	//getMyGeoAddress($latlngloca);	
				//$res2='<a href=http://maps.google.com/maps?q='.$pos1.','.$pos2.' target=_blank title=click here>'.$pos1.','.$pos2.'</a>';	
				//$endPoint = $res2;
				$endPoint = getMyGeoAddress($pos1,$pos2);
				$endPt = $pos1.','.$pos2;
				
				$avgSpeed += $data3[3];
				
				$avgSpeed  = round(($avgSpeed/$k1),2);
				
				$pits3 =  $pos1;
				$pits4 =  $pos2;
				
				$dist = getDistance($pits1, $pits2, $pits3, $pits4);
				$totDist += $dist;
				$pits1 =  $pits3;
				$pits2 =  $pits4;
				
				$finaTime=$strPoint."#".$strTime."#".$endPoint."#".$endTime."#".gmdate("H:i:s",(strtotime($endTime) - strtotime($strTime)))."#".round($totDist)."#".round($avgSpeed)."#".$device."#".date('d-m-Y',strtotime($sdate))."#".$strPt."#".$endPt;
				//echo "<br>";
				//echo "---------------------------------------------------------------------------------------------------------------------------------------------";
				//echo "<BR>";
				
				if($flag == 0)
				{
				$strTime='';
				$endTime='';
				$strPoint = '';
				$strPt = '';
				$endPt  = '';
				$endPoint = '';
				$pits1 =  '';
				$pits2 =  '';
				$pits3 =  '';
				$pits4 =  '';
				$totDist = 0;
				$avgSpeed = 0;
				}
				array_push($timediff, $finaTime);
				
			}
				$cnt++; 

				array_push($timeArr,$geoTime);
			}
		}
		}
		}
	}
	fclose($file1);
	}
}

return($timediff);
}

if($recordUserInfo[ci_clientType] == "Client" && $recordUserInfo[ui_isAdmin] == "1")
{
	$devices_query =  "SELECT * FROM tb_deviceinfo,tb_client_subscription WHERE tcs_isActive = 1 AND tcs_deviceId = di_id AND di_clientId =".$_SESSION[clientID]." AND di_status = 1 ORDER BY di_deviceName,di_deviceId ASC";
}
else if($recordUserInfo[ci_clientType] == "Client" && $recordUserInfo[ui_isAdmin] == "0" && $recordUserInfo[ui_roleId] == "1")
{
	$devices_query = "SELECT * FROM tb_deviceinfo,tb_client_subscription WHERE tcs_isActive = 1 AND tcs_deviceId = di_id AND di_status = 1 AND di_clientId=".$_SESSION[clientID]." AND di_assignedUserId = ".$_SESSION[userID]." ORDER BY di_deviceName,di_deviceId ASC";
}
//echo $devices_query;
//$devices_query =  "SELECT * FROM tb_deviceinfo WHERE di_clientId =".$_SESSION[clientID]." AND di_status = 1 ORDER BY di_deviceName,di_deviceId ASC";
$devices_resp = mysql_query($devices_query);	
?>
<script type="text/javascript" language="javascript">
function showFormDiv()
{
	if(document.getElementById('formDiv').style.display=='none')
	{
		document.getElementById('formDiv').style.display = 'block';
		document.getElementById('shLink').innerHTML = "Hide Form";
	}
	else
	{
		document.getElementById('formDiv').style.display = 'none';
		if(document.getElementById('shLink'))
		document.getElementById('shLink').innerHTML = "Show Form";
	}
}
function showPreloader()
{
	var returnVal = validateMapReport()
	if(returnVal == 1)
	{
		document.getElementById('popup_div').innerHTML = '<div id="loading_txt" >Loading...</div>';
		document.frm_map_filter.submit();
	}
}

function hidePreLoader()
{
	document.getElementById('popup_div').innerHTML = '&nbsp;';
}
function openPath(vid,date,frmTime,toTime)
{
	document.frmTripData.txtVehino.value = vid;
	document.frmTripData.txtDate.value = date;
	document.frmTripData.txtFromTime.value = frmTime;
	document.frmTripData.txtToTime.value = toTime;
	document.frmTripData.submit();
}

function validateMapReport()
{
  if(document.getElementById('map_device_id').value== 0 )
  {
   alert("Select Device"); 
   document.getElementById('map_device_id').focus();
   return 0;  
  }
  
  if(document.getElementById('from_date').value=='')
  { alert("Select From Date"); document.getElementById('from_date').focus();  return 0;  }
  
  if(document.getElementById('to_date').value=='')
  { alert("Select To Date");  document.getElementById('to_date').focus(); return 0; }
  
  
	 var t1=document.getElementById('from_date').value ;
        var t2=document.getElementById('to_date').value;

        var one_day=1000*60*60*24; 
		var x=t1.split("-");     
        var y=t2.split("-");
        var date1=new Date(x[2],(x[1]-1),x[0]);
  
        var date2=new Date(y[2],(y[1]-1),y[0]);
        var month1=x[1]-1;
        var month2=y[1]-1;
        var diff=Math.ceil((date2.getTime()-date1.getTime())/(one_day)); 

         
		 if(diff < 0){
       alert("From Date should be prior to To Date."); document.getElementById('to_date').select();return 0;

		 }
	
	return 1;
	
}
jQuery(function() {





//$("#time3, #time4").timePicker();
 $("#time3, #time4").timePicker({
  startTime: "12:0 AM", // Using string. Can take string or Date object.
  endTime: "11:59 PM", // Using Date object here.
  show24Hours: false,
  separator: ':',
  step: 1});    
	
// Store time used by duration.
var oldTime = $.timePicker("#time3").getTime();

// Keep the duration between the two inputs.
$("#time3").change(function() {
  if ($("#time4").val()) { // Only update when second input has a value.
	// Calculate duration.
	var duration = ($.timePicker("#time4").getTime() - oldTime);
	var time = $.timePicker("#time3").getTime();
	// Calculate and update the time in the second input.
	$.timePicker("#time4").setTime(new Date(new Date(time.getTime() + duration)));
	oldTime = time;
  }
});
// Validate.
$("#time4").change(function() {
  if($.timePicker("#time3").getTime() > $.timePicker(this).getTime()) {
	$(this).addClass("error");
  }
  else {
	$(this).removeClass("error");
  }
});

});
function sendCSVData()
{
//alert(c1);
document.frmTripData.submit();
//	window.location.href='export.php?csvData='+c1+'&frdate='+c2+'&frtime='+c3+'&totime='+c4+'&vehino='+c5;
	//document.write('export.php?csvData='+c1+'&frdate='+c2+'&frtime='+c3+'&totime='+c4+'&vehino='+c5);
}
$(function() {
	$( "#from_date" ).datepicker({
		changeMonth: true,
		changeYear: true,
		maxDate: 0,
		showOn: "button",
		buttonImage: "images/calendar.gif",
		buttonImageOnly: true,
		dateFormat : "dd-mm-yy"
	});
});
$(function() {
	$( "#to_date" ).datepicker({
		changeMonth: true,
		changeYear: true,
		maxDate: 0,
		showOn: "button",
		buttonImage: "images/calendar.gif",
		buttonImageOnly: true,
		dateFormat : "dd-mm-yy"
	});
});
</script>

<div id="formDiv">
<form id="frm_map_filter" name="frm_map_filter" method="post" action="" onsubmit="return validateMapReport();">      	 
<table class="gridform_final">
<tr><th colspan="7">Trip Report</th></tr>
  <tr>
    <td width="8%" align="right"><span class="form_text">Select Device&nbsp;</span></td>
    <td width="15%" align="left">
        <select name="map_device_id" id="map_device_id" tabindex="1" style="width:100%">
        <option value="0">Select Device</option>
         <?php 
		while($devices_fetch = @mysql_fetch_assoc($devices_resp)) 
		{ 
			$renewDate = date("d-m-Y",strtotime("-1 days ".$devices_fetch[tcs_renewalDateTo]));
			//echo $date_offline." <= ".date("d-m-Y",strtotime($renewDate))."<br>";
			if(strtotime(date('d-m-Y')) <= strtotime($renewDate))
			{
			if($devices_fetch[di_deviceName])
				$devName = $devices_fetch[di_deviceName];
			else
				$devName = $devices_fetch[di_deviceId];
        ?>
        <option value="<?php echo $devName."#".$devices_fetch[di_imeiId]; ?>" 
        <?php if($_POST[map_device_id] == $devName."#".$devices_fetch[di_imeiId]) echo "selected"; ?>><?php echo $devName; ?></option>
        <?php } } ?>		
        </select>
        <input type="hidden" name="curdate" id="curdate" value="<?php echo date('Y-m-d'); ?>" />
    </td>
    <td width="10%" align="right"><span class="form_text">From Date & Time</span></td>
    <td width="17" align="left">
    <input type="text" name="from_date" id="from_date" readonly="true" size="12" tabindex="2" value="<?php if(isset($_POST[from_date])) echo $_POST[from_date]; else echo date("d-m-Y"); ?>" style="width:33%;"/>&nbsp;
    <span><input type="text" name="time3" id="time3" readonly="true" size="7" tabindex="3" value="<?php if($_POST[time3]) echo $_POST[time3]; else echo "12:01 AM";?>" /></span>
    </td>
    <td width="10%" align="right"><span class="form_text">To Date & Time</span></td>
    <td width="17%">
    <input type="text" name="to_date" id="to_date" size="12" style="width:40%;" tabindex="4" readonly="true" value="<?php if(isset($_POST[to_date])) echo $_POST[to_date]; else echo date("d-m-Y"); ?>" />&nbsp;
    <span><input type="text" name="time4" id="time4" readonly="true" size="7" tabindex="5" value="<?php if($_POST[time4]) echo $_POST[time4]; else echo "11:59 PM";?>" /></span>
    </td>
    <td width="21%" style="text-align:center">
    <input type="button" name="map_filter_btn"   value="Filter" class="save_btn" tabindex="6"  onclick="showPreloader();"/>
    <input type="hidden" name="map_filter_btn" value="Filter" />
    <input type="button" name="map_cancel_btn" id="map_cancel_btn" value="Reset" class="save_btn" onclick="location.href='index.php?ch=daily';" tabindex="7" /> 
   </td>
  </tr>
</table>
</form>
</div>	
<div id="popup_div" style=" display:block; border:0px;" >

</div>
<?php
if(isset($_POST[map_filter_btn]) && $_POST[map_filter_btn]!='')
{
$sdate = $_POST[from_date];
$edate = $_POST[to_date];
$srcData = explode("#",$_POST[map_device_id]);

$strtTime = explode(":",date("H:i",strtotime($_POST[time3])));
$strtTime = (($strtTime[0] * 60) + $strtTime[1]);

$endTime = explode(":",date("H:i",strtotime($_POST[time4])));
$endTime = (($endTime[0] * 60) + $endTime[1]);

?>
<div class="info_port">Trip Report - <?php echo $srcData[0];?></div>
<table cellpadding="0" cellspacing="0" border="0" class="gridform_final" id="example">      
  <thead>
  <tr>
    <th width="5%" >#</th>
    <th width="7%">Date</th>
    <th width="30%">Start  Point & Time</th>
    <th width="30%">End  Point & Time</th>
    <th width="7%">Duration</th>
    <th width="8%" >Avg. Speed(kmph)</th>
    <th width="7%" >Dist. (km)</th>        
    <th width="5%" >Path</th>
  </tr>
 </thead>
 <tbody>
<?php

$timediff1=array();
$timediff2=array();
$timediff3=array();
$timediff4=array();
$totalDistance=0;
$tripdata = "Date,Start Point,Start Time,End Point,End Time,Duration,Avg. Speed,Dist. Covered";
$tripdata .= "@";
$ct=0;
	if($_POST[from_date] == $_POST[to_date])
	{
		$timediff4[]=getTripReport($sdate,$srcData[0],$srcData[1],$strtTime,$endTime,0);
	}
	else
	{
		$z = GetDays($sdate, $edate);
		for($y=0; $y<count($z); $y++)
		{ 
			if($y == 0) 
			{    $strtTime1 = $strtTime;
				$endTime1 = 1439;
				$timediff1[] =getTripReport($z[$y],$srcData[0],$srcData[1],$strtTime1,$endTime1,0);
				
			}
			elseif($y == count($z)-1) 
			{
				$strtTime1 = 0;
				$endTime1 = $endTime;
				$timediff3[] =getTripReport($z[$y],$srcData[0],$srcData[1],$strtTime1,$endTime1,0);
			}
			elseif($y < count($z)-1) 
			{
				$strtTime1 = 0;
				$endTime1 = 1439;
				$timediff2[] =getTripReport($z[$y],$srcData[0],$srcData[1],$strtTime1,$endTime1,0);
			}
		}
		$timediff4 = array_merge_recursive($timediff1,$timediff2,$timediff3);
	}


	if(count($timediff4)>0)
	{
	$g = 1;
	for($r=0;$r<count($timediff4);$r++)
	{
      foreach($timediff4[$r] as $timed){
		$tTdiff=explode("#",$timed);
		//print_r($tTdiff);
		
		$strAddr1 = explode(",",$tTdiff[9]);	
		if($tTdiff[0] != 0)
			$strAddr = $tTdiff[0];
		else $strAddr =  getGeocodePOI($strAddr1[0].','.$strAddr1[1]);
			
		$endAddr1 = explode(",",$tTdiff[10]);	
		if($tTdiff[2] != 0)
			$endAddr = $tTdiff[2];
		else
			$endAddr = getGeocodePOI($endAddr1[0].','.$endAddr1[1]);
			//echo $g.' '.$strAddr.' = '.$tTdiff[0].' '.$endAddr.' = '.$tTdiff[2].'<br>';
?> 
	<tr <?php if($r % 2 == 0) { echo 'class="odd_row"';} else { echo 'class="even_row"'; } ?> >
	<td valign="top"><?php echo $g; ?></td>
	<td valign="top"><?php echo $tTdiff[8]; ?></td>
	<td valign="top"><?php echo $strAddr." (".date("h:i:s A",strtotime($tTdiff[1])).")"; ?></td>
	<td valign="top"><?php echo $endAddr." (".date("h:i:s A",strtotime($tTdiff[3])).")"; ?></td>
	<td valign="top"><?php echo date("H:i:s",strtotime($tTdiff[4])); ?></td>
	<td valign="top"><?php echo $tTdiff[6]; ?></td>
    <td valign="top"><?php echo $tTdiff[5]; ?></td>
	<td valign="top"><a href="#" title="Click to see the travelled path" onclick="openPath('<?php echo $srcData[1]; ?>','<?php echo $tTdiff[8]; ?>','<?php echo date("H:i",strtotime($tTdiff[1])); ?>','<?php echo date("H:i",strtotime($tTdiff[3])); ?>')">Path</a></td>
	</tr>
<?php   
	$g++;
	$strAddr1 = '';
	$endAddr1 = '';
	//exit;
}	

	}
	}
 ?>	  
 </tbody>
 </table>
<?php
  
}///end of post

?> 

<form name="frmTripData" id="frmTripData" method="post" action="../tr/" target="_blank">
<input type="hidden" name="txtVehino" id="txtVehino" />
<input type="hidden" name="txtDate" id="txtDate" />
<input type="hidden" name="txtFromTime" id="txtFromTime" />
<input type="hidden" name="txtToTime" id="txtToTime" />
<input type="hidden" name="txtSessId" id="txtSessId" value="<?php echo $_SESSION[clientID];?>" />
<input type="hidden" name="txtRunFlag" id="txtRunFlag" value="0" />

</form>
